import { useAtom, useAtomValue } from "jotai";
import { useQuery } from "@tanstack/react-query";
import { AnimatePresence, m } from "framer-motion";
import { request } from "shared/requests";
import { switchPersonModalVisibleAtom } from "@/store/switchPerson";
import LoadingIcon from "@/assets/icons/loading-circle-rotate.svg?jsx";
import { useSearchParam } from "shared/hooks";
import { defaultUri } from "@/lib/constants";
import { clsxm } from "shared/helpers";

export default function SwitchPersonModal() {
  const [visible, setVisible] = useAtom(switchPersonModalVisibleAtom);
  const currentPersonUri = useSearchParam("uri", defaultUri);

  const { data, isSuccess, isLoading } = useQuery({
    queryKey: ["person"],
    queryFn: () =>
      request<{ uri: string; personName: string }[]>("/ainianpu/person.json"),
  });

  return (
    <AnimatePresence>
      {visible && (
        <>
          <div
            className="absolute inset-0"
            onClick={() => setVisible((p) => !p)}
          />
          <m.div
            initial={{ opacity: 0, scaleY: 0.7 }}
            animate={{ opacity: 1, scaleY: 1 }}
            exit={{ opacity: 0, scaleY: 0.7 }}
            className="absolute inset-x-0 top-[60px] origin-top overflow-hidden bg-white shadow"
          >
            {isLoading && (
              <div className="flex items-center justify-center py-8">
                <LoadingIcon />
              </div>
            )}
            {isSuccess && (
              <div className="my-4 flex max-h-[60dvh] flex-wrap gap-2 overflow-auto px-8">
                {data.map((person) => (
                  <a
                    key={person.uri}
                    href={`/ainianpu?uri=${person.uri}&name=${person.personName}`}
                    target="_blank"
                    className="flex flex-none basis-36 flex-col items-center p-4"
                  >
                    <div
                      className={clsxm(
                        "flex size-20 items-center justify-center overflow-hidden rounded-full bg-[#4C9571] text-2xl text-white",
                        currentPersonUri === person.uri &&
                          "outline-dashed outline-2 outline-offset-8 outline-[#4C9571]",
                      )}
                    >
                      <img
                        className="size-full"
                        src={`/ainianpu/avatars/${person.personName}.png`}
                        alt={person.personName}
                      />
                    </div>
                    <div className="mt-3">{person.personName}</div>
                  </a>
                ))}
              </div>
            )}
          </m.div>
        </>
      )}
    </AnimatePresence>
  );
}
